package jp.co.ysl.test;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

public class ClassInfoUtil {
	HashMap classInfos;

	static ClassInfoUtil instance;

	private ClassInfoUtil() {
		classInfos = new HashMap();
		loadClassInfos();
	}

	private void loadClassInfos() {
		try {
			DocumentBuilder documentBuilder = DocumentBuilderFactory
					.newInstance().newDocumentBuilder();
			Document document = documentBuilder.parse(getClass()
					.getResourceAsStream("/properties/classInfo.xml"));

			NodeList classNodeList = document.getElementsByTagName("class");
			int nodeListLength = classNodeList.getLength();

			for (int i = 0; i < nodeListLength; i++) {
				Element classElement = (Element) classNodeList.item(i);

				String classId = classElement.getAttributes()
						.getNamedItem("id").getNodeValue();
				String classType = classElement.getAttributes().getNamedItem(
						"type").getNodeValue();
				List handlers = getHandlers(classElement);
				classInfos.put(classId, new ClassInfo(classId, classType,
						handlers));
			}
		} catch (Exception e) {

		}
	}

	private List getHandlers(Element classElement) throws Exception {
		List result = new ArrayList();
		NodeList managerNodes = classElement.getElementsByTagName("handler");
		for (int j = 0; j < managerNodes.getLength(); j++) {
			Element managerNode = (Element) managerNodes.item(j);
			result.add(managerNode.getAttributes().getNamedItem("type")
					.getNodeValue());
		}

		return result;
	}

	public static ClassInfoUtil getInstance() {
		if (instance == null) {
			instance = new ClassInfoUtil();
		}
		return instance;
	}

	public ClassInfo getClassInfo(String classId) throws Exception {
		if (classInfos == null) {
			throw new Exception("");
		}

		try {
			ClassInfo classInfo = (ClassInfo) classInfos.get(classId);

			if (classInfo == null)
				throw new Exception("classInfo.xml [" + classId
						+ "] ");

			return classInfo;
		} catch (Exception e) {
			throw e;
		}
	}
}
